package com.qx.chat.websocket.conf;

import org.eclipse.jetty.websocket.api.WebSocketBehavior;
import org.eclipse.jetty.websocket.api.WebSocketPolicy;
import org.eclipse.jetty.websocket.server.WebSocketServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.jetty.JettyRequestUpgradeStrategy;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

import com.qx.chat.websocket.handler.QxWebSocketHandler;
import com.qx.chat.websocket.interceptor.QxWebSocketHandshakeInterceptor;

@Configuration
@EnableWebMvc
@EnableWebSocket
public class QxWebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {

	@Override
	public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
		registry.addHandler(qxWebSocketHandler(), "/webSocketServer")
				.addInterceptors(new QxWebSocketHandshakeInterceptor())
				.setHandshakeHandler(handshakeHandler())
				// 跨域
				.setAllowedOrigins("*");
		//sockjs支持
		registry.addHandler(qxWebSocketHandler(), "/sockjs/webSocketServer")
				.addInterceptors(new QxWebSocketHandshakeInterceptor())
				.withSockJS();
	}

	@Bean
	public WebSocketHandler qxWebSocketHandler() {
		return new QxWebSocketHandler();
	}
	/**
	 * jetty必须要加的
	 * @return
	 */
	@Bean
	public DefaultHandshakeHandler handshakeHandler() {
		WebSocketPolicy policy = new WebSocketPolicy(WebSocketBehavior.SERVER);
		policy.setInputBufferSize(8192);
		policy.setIdleTimeout(0);
		return new DefaultHandshakeHandler(new JettyRequestUpgradeStrategy(new WebSocketServerFactory(policy)));
	}
}
